#!coding: utf-8
# Create your views here.
import sys
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)


import pymongo

from exceptions import Exception

from django.template import Context, Template
from django.conf import settings

settings.configure()

template_path = os.path.abspath(os.path.join(cur_path, '../app/v1/template'))


def generatePage(db, nick, num_iids):
    u = db.user.find_one({'_id':nick})
    if not u:
        raise Exception('db has not user: %s' %(nick))
    try:
        user_type = u['type']
    except:
        user_type = 'C'
    tg_items = db.items.find({'_id':{'$in':num_iids}}).limit(3)
    if tg_items.count(True) != 3:
        raise Exception('%s has not enough goods: %d' %(nick, tg_items.count()))
    y = list(tg_items)
    x = u['tg_temp']
    for xxx in y:
        try:
            fprice = float(xxx['price'])
            xxx['price_a']=int(fprice)
            xxx['price_b']='%.2d' %(int(100*(fprice-xxx['price_a'])))
        except:
            xxx['price_a']=0
            xxx['price_b']='00'
    f = open(os.path.join(template_path, x['html_temp']))
    tempstr = f.read()
    f.close()
    t = Template(tempstr)
    d= {
            'goods_list':y,
            'nick':nick,
            'user_type':user_type,
    }
    page = t.render(Context(d))

    return page

def test_generatePage():
    mongo = pymongo.Connection(port=57324)
    db = mongo.taogold
    page = generatePage(db, 'huiqing_shen', [5577521965, 5577505941, 5845555295])
    print page.encode('utf8')


if __name__ == '__main__':
    test_generatePage()




